package com.totoro.metrics;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;

/**
 * Counter是Gauge的一个特例，维护一个计数器， 可以通过inc()、dec()方法对计数器做修改。
 * Created by Niki on 2018/8/28 14:16
 */
public class CounterDemo {
    private static final MetricRegistry metrics = new MetricRegistry();

    private static Queue<String> queue = new LinkedList<>();

    private static Counter pendingJobs = metrics.counter(MetricRegistry.name(CounterDemo.class, "pedding-jobs"));
//    private static Counter pendingJobs;
//    static {
//        // 向metrics容器注册Counter
//        pendingJobs = new Counter();
//        metrics.register(MetricRegistry.name(CounterDemo.class, "pedding-jobs"), metrics);
//    }

    private static void add(String string) {
        pendingJobs.inc();
        queue.offer(string);
    }

    private static String take() {
        pendingJobs.dec();
        return queue.poll();
    }

    public static void main(String[] args) throws InterruptedException {
        OutputUtil.console(metrics);
        int i = 0;
        while (i < 100) {
            i++;
            add("1");
            Thread.sleep(100);
        }

        Thread.sleep(5000);

        while (i > 20) {
            i--;
            take();
            Thread.sleep(100);
        }
    }

}
